package com.miao.teacher.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;  
import android.preference.PreferenceManager;

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;    
import java.io.InputStreamReader;  
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.net.HttpURLConnection;     
import java.net.URL;  
import java.util.Map;
public class FileUtil {
	public static String SDPATH = Environment.getExternalStorageDirectory().getPath() + "/";  
	public static String getFullPath( String AFileOrDir)
	{
		return SDPATH+AFileOrDir;
	}
	public static File[] getFileOrDirList( String ADir)
	{
		File[] ARes = null;
		try
		{
			File AFile = new File(SDPATH+ADir);
			ARes = AFile.listFiles();
		}
		catch(Exception er){ARes = new File[0];}
		return ARes;
	}
	public static String[] getFileOrDirNameList( String ADir)
	{
		String[] ARes = new String[0];
		File[] AFs = getFileOrDirList(ADir);
		ARes = new String[AFs.length];
		for( int i=0;i<AFs.length;i++)
		{
			try 
			{
				ARes[i] = AFs[i].getName();
			}
			catch(Exception er){;}
		}
		return ARes;
	}
	public static void DoCreateDir( String ADir)
	{
		File ADscDir = new File(SDPATH+ADir.replace(SDPATH, ""));
		if ( !ADscDir.exists())
		{
			String AParentDirName = ADscDir.getParent();
			File AParentDir = new File(AParentDirName);
			if (!AParentDir.exists())
			{
				DoCreateDir(AParentDirName );
			}
			try
			{
				ADscDir.mkdir();
			}
			catch(Exception er){
				String Error = er.getMessage();
				String AE = Error;
			}
		}		
	}
	public static String getFilePath( String AFileName)
	{
		String ARes = "";
		try{
			int AEndPos = AFileName.lastIndexOf("/");
			if ( AEndPos>0)
			{
				ARes = AFileName.substring(0, AEndPos );
			}
		}
		catch(Exception er){;}
		return ARes;
	}
	public static Boolean DoWriteTextFile( String AFileName, String AText)
	{
		Boolean ARes = false;
		try
		{ 
			String APathStr= getFilePath( AFileName);
			File APath = new File(SDPATH+ APathStr);
			if (!APath.exists())
			{
				DoCreateDir(APathStr);
			}
			if ( APath.exists())
			{
				try{ 
					String AFullFileName = SDPATH+ AFileName;
					File AFile = new File( AFullFileName);
					AFile.createNewFile();
			        FileOutputStream fout = new FileOutputStream(AFullFileName  );
			        byte [] bytes = AText.getBytes(); 
			        fout.write(bytes); 
			        fout.close(); 
			        ARes = true;
			        }
				catch(Exception e){
					String Error = e.getMessage();
					String AE = Error;
				}
			}
		}
		catch(Exception er){;}
		return ARes;
	} 
	public static boolean SaveByteFile(byte[] mdata,String mFileName,String mPath)
	{
		boolean mRes=false;
		try{
			File APath = new File(SDPATH+ mPath);
			if (!APath.exists())
			{
				DoCreateDir(mPath);
			}
			if ( APath.exists())
			{
				try{ 
					String AFullFileName = SDPATH+ mPath+mFileName;
					File AFile = new File( AFullFileName);
					if(AFile.exists())
					{
						return mRes;
					}
					AFile.createNewFile();
			        FileOutputStream fout = new FileOutputStream(AFullFileName  );
			        fout.write(mdata); 
			        fout.close(); 
			        mRes = true;
			        }
				catch(Exception e){
					String Error = e.getMessage();
					String AE = Error;
				}
			}
		}catch(Exception er)
		{}
		return mRes;
	}
	public static boolean SaveByteFile2(byte[] mdata,String mFileName,String mPath)
	{
		boolean mRes=false;
		try{
			File APath = new File(SDPATH+ mPath);
			if (!APath.exists())
			{
				DoCreateDir(mPath);
			}
			if ( APath.exists())
			{
				try{ 
					String AFullFileName = SDPATH+ mPath+mFileName;
					File AFile = new File( AFullFileName);
					if(AFile.exists())
					{
						AFile.delete();
					}
					AFile.createNewFile();
			        FileOutputStream fout = new FileOutputStream(AFullFileName  );
			        fout.write(mdata); 
			        fout.close(); 
			        mRes = true;
			        }
				catch(Exception e){
					String Error = e.getMessage();
					String AE = Error;
				}
			}
		}catch(Exception er)
		{}
		return mRes;
	}
	public static String DoReadTextFile( String AFileName )
	{
		String ARes = "";
		try
		{
			String AFullFileName=SDPATH+ AFileName;
			File AFile = new File( AFullFileName);
			if (AFile.exists())
			{
				try {
					FileInputStream fis=new FileInputStream(AFile);
					try {
						byte[] b=new byte[fis.available()];
						fis.read(b);
					    fis.close();
						String str2=new String(b);
						ARes = str2;
					} catch (IOException e) {;}
				}
				catch(Exception er) {;}
			}
		}
		catch(Exception er){;}
		return ARes;
	}
	public static String getUrlText( String AUrl )
	{
		String ARes = "";
		try
		{
			URL url=new URL(AUrl);   
            HttpURLConnection conn=(HttpURLConnection)url.openConnection();   
            InputStream input=conn.getInputStream();   
            BufferedReader in=new BufferedReader(new InputStreamReader(input));   
            String line=null;   
            StringBuffer sb=new StringBuffer();   
            while((line=in.readLine())!=null){   
                sb.append(line);   
            }   
            ARes = sb.toString();
		}
		catch(Exception er){;}
		return ARes;
	}
	public static Boolean DoDownload(String AUrl,String AFileName)
	{
		Boolean ARes = false;
		try
		{
			String ATxt = getUrlText(AUrl);
			ARes = DoWriteTextFile(AFileName, ATxt);
		}
		catch(Exception er){;}
		return ARes;
	}
	public static InputStream StringTOInputStream(String in) {
		ByteArrayInputStream is=null;
		try
		{
			is = new ByteArrayInputStream(in.getBytes("UTF-8"));
		}
		catch(Exception er){;}
		return is;  
	}
    public static boolean DoDelFile(File file) {  
        if (file.isDirectory())  
            return false;  
        else
        	
        return file.delete();  
    }
    public static boolean DoDelFile(String AFileName) {  
        boolean ARes = false;
        try
        {
        	File Af = new File( SDPATH+  AFileName);
        	if ( Af.isFile())
        	{
        		if ( Af.exists())
        		{
        			ARes = Af.delete();
        		}
        	}
        }
        catch(Exception er){
        	;
        }
        return ARes;
    }  
	public static String InputStreamTOString(InputStream in ) {
		String Ares ="";
		try
		{
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();		
			int BUFFER_SIZE = 4096;
			byte[] data = new byte[BUFFER_SIZE];  
			int count = -1;  
			while((count = in.read(data,0,BUFFER_SIZE)) != -1)  
				outStream.write(data, 0, count);
			data = null;
			Ares = new String(outStream.toByteArray(),"UTF-8");
		}
		catch(Exception er){;}
		return Ares;  
	}
	// 配置文件操作
	public static void addPreferences(Context context, Map<String, String> map) {
		SharedPreferences mPerferences = PreferenceManager
				.getDefaultSharedPreferences(context);

		SharedPreferences.Editor mEditor = mPerferences.edit();

		if (null != map) {
			for (Map.Entry<String, String> entry : map.entrySet()) {
				mEditor.putString(entry.getKey(), entry.getValue());
			}
		}
		mEditor.commit();
	}
	

	public static void addPreferences(Context context, String key, String value) {
		SharedPreferences mPerferences = PreferenceManager
				.getDefaultSharedPreferences(context);

		SharedPreferences.Editor mEditor = mPerferences.edit();

		mEditor.putString(key, value);

		mEditor.commit();
	}

	public static void addIntPreferences(Context context, String key, int value) {
		SharedPreferences mPerferences = PreferenceManager
				.getDefaultSharedPreferences(context);

		SharedPreferences.Editor mEditor = mPerferences.edit();

		mEditor.putInt(key, value);

		mEditor.commit();
	}
	public static String getPreferences(Context context, String key) {
		String value = null;
		SharedPreferences mPerferences = PreferenceManager
				.getDefaultSharedPreferences(context);

		value = mPerferences.getString(key, null);

		return value;
	}

	public static int getIntPreferences(Context context, String key) {
		int value = 0;
		SharedPreferences mPerferences = PreferenceManager
				.getDefaultSharedPreferences(context);

		value = mPerferences.getInt(key, -1);

		return value;
	}

	public static void cleanPreferences(Context context) {
		SharedPreferences mPerferences = PreferenceManager
				.getDefaultSharedPreferences(context);

		SharedPreferences.Editor mEditor = mPerferences.edit();
		mEditor.clear();

		mEditor.commit();
	}

	public static void removePreferences(Context context, String key) {
		SharedPreferences mPerferences = PreferenceManager
				.getDefaultSharedPreferences(context);

		SharedPreferences.Editor mEditor = mPerferences.edit();
		mEditor.remove(key);

		mEditor.commit();
	}
}
